/*
 * @Descripttion:
 * @Author: caijj
 * @Date: 2020-11-19 10:24:25
 * @LastEditors: caijj
 * @LastEditTime: 2020-12-28 09:46:54
 */
import router from './router';
import store from './store';
import { Message } from 'element-ui';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import { getToken, removeToken } from '@/utils/auth'; // get token from cookie
import getPageTitle from '@/utils/get-page-title';

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ['/login']; // no redirect whitelist
// const whiteList2 = ['/updatePassword'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // console.log(to, from);
  // start progress bar
  NProgress.start();

  // set page title
  document.title = getPageTitle(to.meta.title);

  // determine whether the user has logged in
  let hasToken = getToken();
  const token = document.cookie.match(/(?<=access_token=).*(?=;)/g);
  if (token && token[0] && !hasToken) {
    console.log(token);
    hasToken = token[0];
  }

  if (hasToken) {
    const r = store.state.user.newRoutes;
    // 路由为空的时候，说明是再刷新，刷新页面的时候，重新获取动态路由
    if (!r.length) {
      // 如果是跳转到登录页面,无需重新获取路由
      if (whiteList.indexOf(to.path) !== -1) {
        next();
        NProgress.done();
      } else {
        store.dispatch('user/getNewRouter').then((res) => {
          next({ path: to.fullPath });
        }).catch(() => {
          removeToken();
          next('/login');
        });
      }
    } else {
      if (to.path === '/login') {
        next({ path: '/' });
        NProgress.done();
      } else {
        const hasGetUserInfo = store.getters.name;
        if (hasGetUserInfo) {
          next();
        } else {
          try {
            // get user info
            // await store.dispatch('user/getInfo')
            next();
          } catch (error) {
            // remove token and go to login page to re-login
            await store.dispatch('user/resetToken');
            Message.error(error || 'Has Error');
            next(`/login?redirect=${to.path}`);
            NProgress.done();
          }
        }
      }
    }

    /* has no token*/
  } else {
    // 登录页面
    if (whiteList.indexOf(to.path) !== -1) {
      next();
      // 注册页面
    } else if (to.path.indexOf('updatePassword') !== -1) { // 如果是修改密码页面，不需要token，不做处理
      next();
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
